import React, { useRef } from 'react';
import { YmReactDnd } from 'ym-design';

const { useDrag } = YmReactDnd;

type DragItem = {
  id: string;
  left: number;
  top: number;
};

const boxStyle: React.CSSProperties = {
  position: 'absolute',
  border: '1px dashed gray',
  backgroundColor: 'white',
  width: '128px',
  height: '40px',
  cursor: 'move',
};

function Box(props: any) {
  const { id, left, top, hideSourceOnDrag, children } = props;
  const dragRef = useRef<HTMLDivElement>(null);

  const [{ isDragging }] = useDrag<DragItem>(
    {
      type: 'box',
      dragNode: dragRef.current,
      item: { id, left, top },
      collect: (monitor) => ({
        isDragging: monitor.isDragging(),
      }),
    },
    [id, left, top, dragRef.current],
  );
  if (isDragging && hideSourceOnDrag) {
    return <div ref={dragRef} />;
  }

  return (
    <div className="box" ref={dragRef} style={{ ...boxStyle, left, top }}>
      {children}
    </div>
  );
}

export default Box;
